$(function(){
	var _id = $_GET['id'] ? $_GET['id'] : 0;
	var img =[];
	var removeImg=[];
	/**
	 * @初始化页面
	 */
	(function() {
		$.get('get-supplier-info', {'id' : _id}, function(data, status) {
			if(status =='success' && data.Ack =='Success'){
				var info = data.Body.list;
				$('#vendor').val(info.supplier_name);
				$('#handle_man').val(info.handle_man);
				$('#supplier_info').val(info.supplier_desc);
				$('#saveSupplier').attr('data-id',info.supplier_id);
				$('#phone').val(info.phone);
				$('#client_type').val(info.type);
				$('#bank').val(info.bank);
				$('#bank_account').val(info.bank_account);
				$('#account_name').val(info.account_name);
				
				var imgs = data.Body.imgs;
				for(var i in imgs){
				
					$('.imglist_addwindow1').prepend('<li  name="picture"  data-path="'+imgs[i].supplier_img+'"><a href="'+imgs[i].supplier_img+'" data-lightbox="aa"><img src="'+imgs[i].supplier_img+'" width="190px" height="180px"></a></li>');
					img.push(imgs[i].supplier_img);
					if(i == 0){
						console.log(23);
					} else {
						
					}
					
				}
				
				
				
			}
		})
	})();
	/**
	 * @选择省份,添加城市列表
	 */
	$('#re_province').change(function(){
		$('#re_city').find('option:first').nextAll().remove();//清空城市
		$('#re_district').find('option:first').nextAll().remove();//清空地区
		$.get('get-citys',{'province':$(this).val()},function(data,status){
			if(status =='success'){
				if(data.Ack =='Success'){
					var R = data.Body;
					if(R && R.length){
						for(var i in R){
							$('<option value="'+R[i].region_id+'">'+R[i].region_name+'</option>').appendTo($('#re_city'));
						}
					}
				} else {
				}
			} else {
				alertTips('error','网络错误！');
			}
			
		})
		
	});
	
	/**
	 * @desc 选择城市，添加地区
	 */
	$('#re_city').change(function(){
		$('#re_district').find('option:first').nextAll().remove();//清空地区
		$.get('get-district',{'city':$(this).val()},function(data,status){
			if(status == 'success'){
				if(data.Ack =='Success'){
					var R = data.Body;
					if(R && R.length){
						for(var i in R){
							$('<option value="'+R[i].region_id+'">'+R[i].region_name+'</option>').appendTo($('#re_district'));
						}
					}
				} else {
				}
			} else{
				alertTips('error','网络错误！');
			}
		})
	});
	
	//返回到上一页
	$('#backUrl').on('click',function(){
		window.history.go(-1);
	})
	/**
	 *@desc 验证提交数据
	 */
	var validateInfo = function(){
		$('#newSupplier').validate({
			rules : {
				vendor : {
					required : true,
					minlength : 2,
					remote : '/supplier/check-supplier?type=vendor&id=' + _id,
				},
				handle_man:{
					required:true,
				},
				re_city:{
					required:true,
				},

			},
			messages : {
				vendor : {
					required : "请输入供应商名称",
					minlength : "供应商名最少两个字母组成",
					remote : "此供应商名称已存在",
				},
				re_city:{
					required:"请选择城市",
				},

			},
			submitHandler : function(form) {
				saveSupplier();
			}
		});
	}
	
	$('#saveSupplier').on('click',function(){
		validateInfo();
	});
	
	//保存供应商
	function saveSupplier()
	{
		var dis_count = $('#re_district').find('option').length;
		var dis_select = $('#re_district').find('option:selected').val();
		if(dis_count > 1){
			if(dis_select == undefined || dis_select == 0){
				alertTips('warning','请选择地区');
				return false;
			}
		}
		var supplier_info = {
			'id' : $('#saveSupplier').attr('data-id'),
			'sname':$('#vendor').val(),
			'desc':$('#supplier_info').val(),
			'man':$('#handle_man').val(),
			'country':$('#re_country').val(),
			'province':$('#re_province').val(),
			'city':$('#re_city').val(),
			'district':$('#re_district').val(),
			'phone':$('#phone').val(),
			'client_type':$('#client_type').val(),
			'bank':$('#bank').val(),
			'bank_account':$('#bank_account').val(),
			'account_name' :$('#account_name').val(),
		}
		
		$.get('save-supplier',supplier_info,function(data,status){
			if(status =='success'){
				if(data.Ack =='Success'){
					alertTips('success','保存成功!');
					window.location.reload();
				} else {
					alert('error','保存失败!');
				}
			}
		})
	}
	
	//重置
	$('#reset').on('click',function(){
		window.location.reload();
	});
	
	//图片管理
    $('#determine').on('click',function(){
	    if($('#imglistli').find('li').length==0){
	      	alertTips('warning','请选择上传图片！');
	        return;
	     }
	    $('.addImgTC').hide();   	
	    $('.imglist_addwindow1').find('li[name="picture"]').remove();
        for(var i in img){
        	$('.imglist_addwindow1').prepend('<li name="picture" data-path="'+img[i]+'"><a href="'+img[i]+'" data-lightbox="aa"><img src="'+img[i]+'" width="190px" height="180px"></a></li>');
        }
	      
	   });
	
    //图片上传
    (function(){
        $("#drop-area-div").dmUploader({
            url:'upload-pic',
            // allowedTypes:'image/jpg,image/png', //chrome 打开选择图片文件夹会很慢
            extFilter:'jpg;png;gif;bmp;tif',
//            maxFiles:5,
            maxFileSize:1024*1024,
            dataType:'json',
            fileName:'Filedata',
            onInit: function(){},
            onFallbackMode: function(message){},
            onNewFile: function(id, file){},
            onBeforeUpload: function(id){
                if(img.length>=5){
                	alertTips('warning','最多只能上传5张图片！'); 
                    $("#drop-area-div").find('input').attr('disabled','disabled');
                    return false;
                }
            },
            onComplete: function(){},
            onUploadProgress: function(id, percent){},
            onUploadSuccess: function(id, data){
                if(data.Ack == 'Success'){
                    img.push(data.Body.filepath);
                    $('<li><i class="icon-close iconBtnS" title="点击删除" data-id="'+id+'"></i><img src="'
                        +data.Body.filepath+'" width="70px" height="60px"></li>').appendTo('.imglist_addwindow');
                }else{
                	alertTips('error','上传出错,请重试！');
                    return false;
                }
            },
            onUploadError: function(id, message){
            	alertTips('error','网络错误,图片上传失败！');
            },
            onFileTypeError: function(file){
            	alertTips('error','图片类型错误！');
            },
            onFileSizeError: function(file){
                alertTips('error','图片大小超过限制！');
            },
            onFileExtError: function(file){
            	alertTips('error','不允许扩展名类型！');
            },
            onFilesMaxError: function(file){
                alertTips('error','图片数量超过限制！');
            }
        });
    })();
    // 点击添加附件事件
    $('#uploadPic').on('click',function(){
    	if(_id == 0){
    		alertTips('error','请先保存供应商信息');
    		return false
    	}
        $('.addImgTC').show();
        $('.imglist_addwindow').empty();
        for(var i in img){
        	$('<li><img src="'+img[i]+'" width="70px" height="60px"></li>').appendTo('.imglist_addwindow');
        }
    });
    // 点击关闭添加文件窗口
    $('#cancelUserPic').on('click',function(){
        $('.addImgTC').hide();
       $('.imglist_addwindow1').find('li[name="picture"]').remove();
        for(var i in img){
        	$('.imglist_addwindow1').prepend('<li  name="picture"  data-path="'+img[i]+'"><a href="'+img[i]+'" data-lightbox="aa"><img src="'+img[i]+'" width="190px" height="180px"></a></li>');
        }
    });
    
    // 删除添加窗口的图片列表
    $('.imglist_addwindow,.imglist_addwindow1').on('click','.icon-close',function(){
    	var IMG = $(this);
    	layer.confirm('是否删除图片?', {icon: 7, title:'提示'}, function(index){
    		  //do something
    		 var picurl = IMG.parents('li').find('img').attr("src");
    		 removeImg.push(picurl);
    	     img.splice($.inArray(picurl,img),1);
    	     IMG.parent().remove();
    	     /*  if(!img.length){
    	         $('.imgShow').hide();
    	     }*/
    	     // 启用控件
    	     $("#drop-area-div").find('input').removeAttr('disabled');
    		 layer.close(index);
    	});
       
    });
    
    //编辑
    $('#eidtFile').on('click', function(){
    	$('.imglist_addwindow1 li').each(function(index,element){
    		$(element).prepend('<i class="icon-close iconBtnS" title="点击删除"></i>');
    	})
    })
    
    //保存
    $('#saveFile').on('click', function(){
    	if(_id == 0){
    		alertTips('error','请先保存供应商信息！');
    		return false
    	}
    	if(!img){
    		alertTips('error','请上传供应商附件！');
    		return false
    	}
    	$('.imglist_addwindow1 li').each(function(index,element){
    		$(element).find('.iconBtnS').remove();
    	})
    	
    	$.post('save-img',{'img':img, 'rmimg':removeImg,'supid': _id},function(data, status){
    		if(status =='success'){
    			if(data.Ack =='Success'){
    				alertTips('success','保存成功！');
    				return ;
    			} else {
    				alertTips('error','保存失败！');
    				return false;
    			}
    		} else {
    			alertTips('error','网络错误!');
    			return false;
    		}
    	})
    	
    })
});